const router = require("koa-router");
const fs = require("fs");
const stream = require("stream");
const menuData = require("./menuData");
const { exec } = require("./mysql");
const Mock = require("mockjs");
const _router = router();
const send = require("koa-send");
const upload = require("./multer");
const { promises } = require("dns");
const jwt = require('jsonwebtoken')
/* 账号信息 */
_router.post("/user", async (ctx) => {
  try {
    const headers = ctx.request.header
    const session = global.atob(headers['g-session'])
    const sql = `select * from userinfo where userName='${session}'`
    const data = await exec(sql)
    return ctx.success(data[0], "success");
  } catch (error) {
    console.log({error});
  }
});
/* 上传 */
_router.post("/upload", upload.single("file"), async (ctx) => {
  try {
    const randomList = "qwertyuiopasdfghjklzxcvbnm0123456789";
    let fileId = "";
    for (let i = 0; i < 8; i++) {
      fileId += randomList[Math.floor(Math.random() * 36)];
    }
    fileId += new Date().getTime();
    const fileName = ctx.req.file.filename;
    const filePath = ctx.req.file.path.replaceAll("\\", '/') // 路径中的\需要转译
    const originalname = ctx.req.file.originalname;
    const fileDate = new Date().format("yyyy-MM-dd hh:mm:ss");
    sql = `insert into files (fileId,fileName,filePath,fileDate,originalname) values ('${fileId}','${fileName}','${filePath}','${fileDate}','${originalname}')`;
    exec(sql);
    return ctx.success({ fileId }, "上传成功");
  } catch (error) {
    return ctx.fail("上传失败");
  }
});
/* 下载 */
_router.get("/downLoad/:name", async (ctx) => {
  const name = ctx.params.name;
  const path = `public/uploads/${name}`;
  ctx.attachment(path);
  await send(ctx, path);
});
_router.post("/downLoad", async (ctx) => {
  try {
    const fileId = ctx.request.body.fileId;
    const sql = `select filePath,fileName from files where fileId='${fileId}'`
    const data = await exec(sql)
    const { filePath, fileName } = data[0] || {}
    const file = await readFile(filePath);
    ctx.set("Access-Control-Expose-Headers", "content-disposition");
    ctx.set("Content-disposition", "attachment;filename=" + `${fileName}`);
    ctx.body = file;
  } catch (error) {
    console.log({ error });
    return ctx.fail("上传失败");
  }
});
function readFile(path) {
  return new Promise((resolve) => {
    fs.readFile(path, (err, data) => {
      resolve(data);
    });
  });
}
/* 查询文件列表 */
_router.post("/queryFileList", async (ctx) => {
  try {
    const sql = "select * from files";
    const data = await exec(sql);
    return ctx.success(data, "");
  } catch (error) {
    console.log({ error });
    return ctx.fail("查询失败");
  }
});
/* 登录 */
_router.post("/login", async (ctx) => {
  try {
    const account = ctx.request.body.account
    const password = ctx.request.body.password
    const sql = "select * from userinfo";
    const data = await exec(sql);
    const userData = data.find(
      (item) => item.userName == account
    );
    if (userData) {
      if (
        account === userData.userName &&
        password === userData.password
      ) {
        const data = {
          session: '',
          token: ''
        }
        const payload = { userName: userData.userName, iat: new Date().getTime(), exp: Math.floor(Date.now() / 1000) + (60 * 60 * 10) }  /* 十小时有效期 */
        data.token = jwt.sign(payload,'secret');
        data.session = global.btoa(account)
        return ctx.success(data, "success");
      }
      return ctx.fail("账号或密码错误");
    } else {
      return ctx.fail("该账号不存在");
    }
  } catch (error) {
    console.log(error);
  }
});
/* 菜单 */
_router.post("/menu", async (ctx) => {
  return ctx.success(menuData);
});

_router.post("/queryTable", async (ctx) => {
  let sql = "select * from querytable_data";
  const data = await exec(sql);
  const params = ({ limit, page } = ctx.request.body);
  if (ctx.verify(params, 2)) {
    let newData = data.slice((page - 1) * limit, page * limit);
    return ctx.success(newData, "", data.length);
  } else {
    return ctx.fail();
  }
});
/* 表格删除 */
_router.post("/tableDelete", async (ctx) => {
  const { userName } = ctx.request.body;
  if (userName) {
    let sql = `delete  from querytable_data where name="${userName}"`;
    try {
      await exec(sql);
      return ctx.success(null, "删除成功");
    } catch (err) {
      console.log({ err });
      return ctx.fail("删除失败");
    }
  } else {
    return ctx.fail("缺少参数,删除失败");
  }
});
/* 表格编辑 */
_router.post("/edit/queryTable", async (ctx) => {
  let rowData = ctx.request.body;
  let sql = "";
  if (!ctx.verify(rowData, 7)) return ctx.fail("缺少参数,修改失败");
  try {
    for (const key in rowData) {
      console.log(key, rowData[key]);
      sql = `update querytable_data set ${key}='${rowData[key]}' where Id='${rowData.Id}'`;
      await exec(sql);
    }
    return ctx.success(null, "修改成功");
  } catch (error) {
    return ctx.fail("修改失败");
  }
});
/* 表格新增 */
_router.post("/add/queryTable", async (ctx) => {
  let rowData = ctx.request.body;
  let sql = "";
  console.log(ctx.request.body);
  if (!ctx.verify(rowData, 6)) return ctx.fail("缺少参数,增加失败");
  try {
    const { age, name, sex, address, title, email } = rowData;
    sql = `insert into querytable_data (age,name,sex,address,title,email) values ('${age}','${name}','${sex}','${address}','${title}','${email}')`;
    exec(sql);
    return ctx.success(null, "增加成功");
  } catch (error) {
    console.log(error);
    return ctx.fail("增加失败");
  }
});
module.exports = _router;
